import Request from '@/utils/luch-request/index.js'
import baseUrl from './config.js'
import login from '@/utils/login'
import storage from "@/utils/storage"
const http = new Request()
import store from '@/store'
http.setConfig((config) => {
	config.baseURL = baseUrl
	return config
})

http.interceptors.request.use(config => { // 可使用async await 做异步操作
	if (config.method === "POST" && config.data) {
		config.params = config.data.params
	}
	// console.log('请求', config)
	const TOKEN = storage.getStorage('access_token')
	config.header['token'] = TOKEN
	// config.header['token'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyRmxhZyI6MCwiZW50RmxhZyI6MCwic2VydmVyRmxhZyI6MSwiZXhwIjoxNzExNTkyNDA1LCJ1c2VySWQiOjE4ODg0LCJpYXQiOjE3MTAyOTY0MDV9.a_IYNRJu_yCFIzxxgD2Ee55OaDrfXSxS35zFLY_Vd_M'
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

http.interceptors.response.use(
	async  res => {
		const { code, data } = res.data
	// console.log('响应', res.data)
		if (code === 500) {
			uni.showToast({
				title: data || 'error',
				icon: "none",
				duration: 3000
			});
		}
		if (code === 9999) {
  		

			uni.showToast({
				title: data || 'error',
				icon: "none",
				duration: 2000
			});
			login().then(() => {
				
				// 获取当前页面栈
				// const pages = getCurrentPages();
				// // 获取栈顶页面
				// const currentPage = pages[pages.length - 1];
				// console.log(currentPage)
				// // 获取页面的路径
				// const pagePath = currentPage.$page.fullPath;
				// console.log(pagePath)
				// // currentPage.onUnload()
				// currentPage.onLoad()
				// 使用函数判断
				uni.showToast({
					title: '登录成功',
					icon: "none",
					duration: 2000
				});
				setTimeout(() => {
					// store.commit('setTabIndex', 0)
					// uni.switchTab({
					// 	url: '/pages/home/index',
					// })
					const currentPage = getCurrentPages().pop();
					if (currentPage) {
						const url = currentPage.$page.fullPath;
						uni.redirectTo({
							url,
							fail: () => {
								store.commit('setTabIndex', 0)
								uni.switchTab({
									url: '/pages/home/index',
								})
							}
						});
						// 可以在这里保存 url 到本地存储或全局变量中
					} else {
						store.commit('setTabIndex', 0)
						uni.switchTab({
							url: '/pages/home/index',
						})
					}
				}, 2000)
			}).catch(err => {
				uni.navigateTo({
					url: '/pages/login/index'
				})
			})
			
		}
		return res.data
	}, error => {
		const {
			statusCode
		} = error
		let msg = ''
		switch (statusCode) {
			case 404:
				msg = `${statusCode}（未找到）`
				break;
			case 500:
				msg = `${statusCode}（服务器内部错误）`
				break;
			default:
				break;
		}
		uni.showToast({
			title: msg || 'error',
			icon: "none",
			duration: 2000
		});
		uni.hideLoading()
		return Promise.reject(error);
	}
)


export default http
